package com.qinsong.myapplication.controller.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseContactListFragment;
import com.hyphenate.exceptions.HyphenateException;
import com.qinsong.myapplication.R;
import com.qinsong.myapplication.controller.activity.ChatActivity;
import com.qinsong.myapplication.controller.activity.InvitationActivity;
import com.qinsong.myapplication.controller.activity.addContactActivity;
import com.qinsong.myapplication.model.Model;
import com.qinsong.myapplication.model.bean.UserInfo;
import com.qinsong.myapplication.utils.Constant;
import com.qinsong.myapplication.utils.SpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 联系人会话列表
 */
public class ContactListFragment extends EaseContactListFragment {


    private ImageView iv_contact_redpoint;
    private LocalBroadcastManager mLBM;
    private BroadcastReceiver ContactInviteChangeReceiver = new BroadcastReceiver() {
        //接受方法
        @Override

        public void onReceive(Context context, Intent intent) {
                //更新红点信息
            iv_contact_redpoint.setVisibility(View.VISIBLE);
            SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,true);
        }
    };
    private BroadcastReceiver ContactChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            refreshContactList();
        }
    };
    private LinearLayout haoyou;
    private String mhxid;

    @Override
    protected void initView() {
        super.initView();
        //添加图片
        titleBar.setRightImageResource(R.drawable.em_add);

        //头布局
        View headerView=View.inflate(getActivity(),R.layout.header_fragment_contact,null);
        listView.addHeaderView(headerView);
        //获取红点
        iv_contact_redpoint = headerView.findViewById(R.id.iv_contact_redpoint);
        //获取好友 邀请信息条目对象
        haoyou = headerView.findViewById(R.id.haoyou);
        //设置好友列表条目点击事件
        setContactListItemClickListener(new EaseContactListItemClickListener() {
            @Override
            public void onListItemClicked(EaseUser user) {
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                //传递参数
                intent.putExtra(EaseConstant.EXTRA_USER_ID,user.getUsername());
                startActivity(intent);
            }
        });


    }

    @Override
    protected void setUpView() {
        super.setUpView();
        //添加联系人按钮点击事件
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Intent intent= new Intent(getActivity(),addContactActivity.class);
                startActivity(intent);
            }
        });

        //初始化红点显示
        Boolean isDiplay = SpUtils.getInstance().getBoolean(SpUtils.IS_NEW_INVITE, false);
        iv_contact_redpoint.setVisibility(isDiplay ?View.VISIBLE :View.GONE);
        //还有邀请条目的点击事件
        haoyou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //红点处理
                iv_contact_redpoint.setVisibility(View.GONE);
                SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,false);
                //跳转邀请信息页面
                Intent intent = new Intent(getActivity(),InvitationActivity.class);
                startActivity(intent);
            }
        });

        //注册广播
        mLBM = LocalBroadcastManager.getInstance(getActivity());
        //注册邀请信息变化的广播
        mLBM.registerReceiver(ContactInviteChangeReceiver,new IntentFilter(Constant.CONTACT_INVITE_CHANGED));
        //联系人列表变化广播
        mLBM.registerReceiver(ContactChangeReceiver,new IntentFilter(Constant.CONTACT_CHANGED));
        //从环信服务器获得所有联系人信息
        getContactListFromHxServer();
        //绑定好友列表（haoyou ）和contextmenu
        registerForContextMenu(listView);
    }

    /**
     * 绑定删除按键
     * @param menu
     * @param v
     * @param menuInfo
     */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        //获取该条好友的位置信息
        int position = ((AdapterView.AdapterContextMenuInfo) menuInfo).position;
        //转化为EAsaUser
        EaseUser easeUser = (EaseUser) listView.getItemAtPosition(position);
        mhxid = easeUser.getUsername();
        //添加布局
        getActivity().getMenuInflater().inflate(R.menu.delete,menu);


    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.contact_delete){
            ///执行删除选中的联系人
            deleteContact();
            return  true;
        }
        return super.onContextItemSelected(item);
    }

    /**
     * 删除联系人
     */
    private void deleteContact() {
        Model.getInstance().getGlobaThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().contactManager().deleteContact(mhxid);
                    Model.getInstance().getDbManager().getContactDao().deleteContactByHxId(mhxid);
                    if (getActivity()==null){
                        return;
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //提示
                            Toast.makeText(getActivity(),"删除"+mhxid+"成功",Toast.LENGTH_SHORT).show();
                            //刷新页面
                            refreshContactList();

                        }
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    if (getActivity()==null){
                        return;
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //提示
                            Toast.makeText(getActivity(),"删除"+mhxid+"失败",Toast.LENGTH_SHORT).show();


                        }
                    });
                }
            }
        });
    }

    /**
     * 从环信服务器获取 好友列表信息
     */
    private void getContactListFromHxServer() {
        Model.getInstance().getGlobaThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    List<String> hxids =   EMClient.getInstance().contactManager().getAllContactsFromServer();
                    //判断是否为空
                    if (hxids!=null && hxids.size()>=0){
                        //封装进入到联系人集合
                        List<UserInfo> contacts  = new ArrayList<>();
                        for (String hxid:hxids){
                            UserInfo userInfo = new UserInfo(hxid);
                            contacts.add(userInfo);
                        }
                        //保存好友信息到本地数据库
                        Model.getInstance().getDbManager().getContactDao().saveContacts(contacts,true);
                        //刷新页面
                        if (getActivity()==null){
                            return;
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //刷新好友列表页面方法
                                refreshContactList();
                            }
                        });
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 刷新好友列表页面方法
     */
    private void refreshContactList() {
        //获取数据
        List<UserInfo> contacts = Model.getInstance().getDbManager().getContactDao().getContacts();
        //判断是否为空
        if (contacts!=null && contacts.size()>=0){
            //设置数据（esui提供）
            Map<String, EaseUser> contactsMap = new HashMap<>();
            //数据类型转换
            for (UserInfo contact :contacts){
                EaseUser easeUser = new EaseUser(contact .getHxid());
                contactsMap.put(contact .getHxid(),easeUser);
            }
            setContactsMap(contactsMap);
            refresh();
        }
    }

    /**
     * 销毁广播
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        mLBM.unregisterReceiver(ContactInviteChangeReceiver);
        mLBM.unregisterReceiver(ContactChangeReceiver);
    }
}
